package progetto.gruppo0506;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import android.content.Context;
import android.location.Location;
import android.util.Log;

import com.google.android.maps.GeoPoint;

public class DownloadPercorso {
	public static ArrayList<GeoPoint> getPath(Context baseContext,
			Location src, Location dst) {
		ArrayList<GeoPoint> points = new ArrayList<GeoPoint>(0);
		String link = String
				.format("http://maps.google.com/maps?f=d&hl=en&saddr=%f,%f&daddr=%f,%f&ie=UTF8&0&om=0&output=kml",
						src.getLatitude(), src.getLongitude(),
						dst.getLatitude(), dst.getLongitude());
		Log.i("Stringa", link);
		Document doc = null;
		HttpURLConnection urlConnection = null;
		URL url = null;

		try {
			url = new URL(link);
			urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.setRequestMethod("GET");
			urlConnection.setDoOutput(true);
			urlConnection.setDoInput(true);
			urlConnection.connect();

			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			doc = db.parse(urlConnection.getInputStream());
		} catch (Exception e) {
			return null;
		}

		if (doc.getElementsByTagName("GeometryCollection").getLength() > 0) {
			String path = doc.getElementsByTagName("GeometryCollection")
					.item(0).getFirstChild().getFirstChild().getFirstChild()
					.getNodeValue();
			Log.i("Stringa", path);
			Pattern pattern = Pattern
					.compile("(.\\d+\\.\\d+),(.\\d+\\.\\d+),\\d+\\.\\d+\\ ");
			
			Matcher matcher = pattern.matcher(path);
	
			while (matcher.find()) {
				Log.i("Latitudine", matcher.group(2));
				Log.i("Latitudine", matcher.group(1));
				points.add(new GeoPoint((int) (Double.parseDouble(matcher
						.group(2)) * 1E6), (int) (Double.parseDouble(matcher
						.group(1)) * 1E6)));
			}
		} else
			return null;

		return points;
	}
}
